package network.socket.udp;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;

    //服务器的ip和端口
    private String serverIp = null;
    private int serverPort = 0;

    //一次通信需要有两个ip 两个端口号 ：客户端的和服务器的
    //需要将服务器的IP和端口号告诉客户端才可以成功通信
    public UdpEchoClient(String serverIp, int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        System.out.println("客户端启动...");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            //1.读取要发送的数据
            System.out.println("> ");
            String request = scanner.next();
            if(request.equals("exit")){
                System.out.println("Bye!");
                break;
            }
            //2.构造成UDP请求，并发送
            //  InetAddress.getByName(serverIp) --> IP需要填写的是32位整数形式，此时的ip是string 需要用这个方法转换
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);
            //3.读取udp响应 并 解析
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //4.把解析出来的结果显示出来
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1", 9090);
        udpEchoClient.start();
    }
}
